"""
定义
conftest.py 是 pytest 特有的本地测试配置文件，
它可以包含 fixture 函数、钩子函数等，用于为测试用例提供配置和共享的资源。
"""
import pytest
from selenium import webdriver
from webdriver_helper import get_webdriver

from commons import pages
from commons.kdt import Word

login_url = "http://116.62.63.211/shop/user/loginInfo.html"


@pytest.fixture
def anonymity_driver():
    """不进行登录的浏览器"""
    d = get_webdriver()
    yield d
    d.quit()


@pytest.fixture(scope='session')
def user_driver():
    """登录商城"""
    driver = webdriver.Chrome()  # 启动浏览器
    # 隐式等待，最大等待时间为20秒
    driver.implicitly_wait(20)
    driver.get(login_url)
    page = pages.LoginBasePage(driver)
    msg = page.login()
    print("系统提示:", msg)
    assert msg == "登录成功"
    yield driver
    driver.quit()  # 关闭浏览器


@pytest.fixture(scope='session')
def ddd():
    return "123"


def pytest_xlsx_run_step(item):
    """钩子函数：调用excel时，执行每行步骤都会调用一次该函数"""
    # 实例化关键字
    for k, v in item.usefixtures.items():  # 遍历所有fixture
        if "driver" in k:
            driver = v
            wd = Word(driver)
            break
        elif k == "ddd":  # 例子，不用管
            print(v)
        elif k == 'has_default_address':
            driver = v
            wd = Word(driver)
            break

    # 调用实例方法
    key_word_name = item.current_step['标记']  # 关键字名称
    key_word_args = []  # 关键字参数
    for k, v in item.current_step.items():
        if k.startswith("列") and v is not None:  # “列”开头
            key_word_args.append(v)
    func = getattr(wd, key_word_name)
    func(*key_word_args)
    return True


def new_address(driver, alias, name, tel, province, city, county, address, default=False):
    """
    用于创建地址的工具函数
    """
    wd = Word(driver)
    wd.goto('http://116.62.63.211/shop/useraddress/index.html')
    wd.pom('UserAddressIndex', 'new_address')
    wd.pom('UserAddressSave', 'input', alias, name, tel, province, city, county, address, default)
    wd.pom('UserAddressSave', 'submit')
    wd.save_msg("msg")
    wd.assert_equal("${msg}", "操作成功")


@pytest.fixture(scope='module')
def has_default_address(user_driver):
    """
    每次测试:
        初始 创建一个默认，一个非默认地址
        结束 删除全部地址
    """
    new_address(
        user_driver, '别名AAA', '默认地址AAA', '15970794846',
        '江西省', '赣州市', '章贡区', '详细地址',
        default=True
    )
    new_address(
        user_driver, '别名BBB', '非默认地址BBB', '15970794846',
        '江西省', '赣州市', '章贡区', '详细地址'
    )
    yield user_driver
    # 删除全部地址
    wd = Word(user_driver)
    wd.goto('http://116.62.63.211/shop/useraddress/index.html')
    wd.pom("UserAddressIndex", "del_address_all")
    wd.sleep("1")
